package netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;



/**
 * @author ：朱博
 * @description：自定义服务处理器 1、#{SimpleChannelInboundHandler} ChannelInboundHandlerAdapter 是其子类
 * 2、#{HttpObject} 表示客户端服务器端的相互通信的数据被封装成一个HttpObject对象
 * @date ：2021/4/17 15:29
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            System.out.println(msg.getClass());
            System.out.println(ctx.channel().remoteAddress());
            //恢复消息给浏览器
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello 我是服务器", CharsetUtil.UTF_8);

            HttpRequest httpRequest = (HttpRequest) msg;
            String uri = httpRequest.uri();
            if("/favicon.ico".equals(uri)){
                return;
            }

            //指定状态码 和协议版本
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

            ctx.writeAndFlush(defaultFullHttpResponse);
        }
    }
}
